package com.whir.rd.service.api.sendFlow;



import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.jdom.Element;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.util.PropertiesReader;
import com.whir.common.db.Dbutil;
import com.whir.common.path.SystemPath;
import com.whir.common.util.DataSourceBase;
import com.whir.common.util.Random;
import com.whir.ezflow.vo.UserInfoVO;
import com.whir.service.api.ezflowservice.EzFLOWForWorkFlow;

public class QMSSendEzFlowService {
	private static Logger logger = Logger.getLogger(QMSSendEzFlowService.class.getName());
    private Connection conn = null;
    private PreparedStatement stat = null;
    private ResultSet rs = null;
    private String rootPath = SystemPath.getRootFilePath();
    
    private void openConn() throws SQLException {
        this.conn = (new DataSourceBase()).getDataSource().getConnection();
    }

    private void closeConn() throws SQLException {
        if (this.rs != null) {
            this.rs.close();
        }

        if (this.stat != null) {
            this.stat.close();
        }

        if (this.conn != null) {
            this.conn.close();
        }

    }
    
    
    public String sendQMSFlowInstance(Element element, String infoId) {
        String result = "0";
        String sendAccounts = element.getChild("sendAccounts").getValue() == null ? "" : element.getChild("sendAccounts").getValue();
        String dealUserAccount = element.getChild("dealUserAccount").getValue() == null ? "" : element.getChild("dealUserAccount").getValue();
        String dutyUnit = element.getChild("dutyUnit").getValue() == null ? "" : element.getChild("dutyUnit").getValue();
        String materialNo = element.getChild("materialNo").getValue() == null ? "" : element.getChild("materialNo").getValue();
        if (dealUserAccount != null && !"".equals(dealUserAccount)) {
            Map<String, String> userMap = this.getUserInfoByAccounts(sendAccounts);
            String userId = (String)userMap.get("userId");
            String userName = (String)userMap.get("userName");
            List<String[]> defaultDealUserList = new ArrayList();

            String deal;
            String sql;
            String account;
            try {
                this.openConn();
                String[] deals = dealUserAccount.split(",");
                String[] var16 = deals;
                int var15 = deals.length;

                for(int var14 = 0; var14 < var15; ++var14) {
                    deal = var16[var14];
                    sql = "select emp_id,empname,useraccounts from org_employee where useraccounts = ?  and userisdeleted = 0 and userisactive=1";
                    this.stat = this.conn.prepareStatement(sql);
                    this.stat.setString(1, deal);
                    this.rs = this.stat.executeQuery();
                    if (this.rs.next()) {
                        String id = this.rs.getString(1);
                        String name = this.rs.getString(2);
                        account = this.rs.getString(3);
                        defaultDealUserList.add(new String[]{id, name, account});
                    }
                }
            } catch (SQLException var29) {
                SQLException e = var29;
                e.printStackTrace();
            } finally {
                try {
                    this.closeConn();
                } catch (SQLException var28) {
                    SQLException e = var28;
                    e.printStackTrace();
                }

            }

            EzFLOWForWorkFlow ezForWork = new EzFLOWForWorkFlow();
            deal = userId;
            
            Properties props = loadProperties("qmsConfig.properties");
            
            String productStageKey = props.getProperty("productStageKey");
            productStageKey = productStageKey==null?"remark1":productStageKey;
//            if(productStageKey==null){
//            	return "-4";
//            }
            
            
            //增加配置数据信息  动态发起流程 start
            String productStageValue = element.getChild(productStageKey).getValue() == null ? "-1" : element.getChild(productStageKey).getValue();
            System.out.println("productStageValue===:"+productStageValue);
            String flowKeyConfig = props.getProperty("flowKeyConfig");
            System.out.println("flowKeyConfig===:"+flowKeyConfig);
//            String processKey = "";
//            JSONArray arr = JSONArray.parseArray(flowKeyConfig);
//    		for(int i=0;i<arr.size();i++){
//    			JSONObject json = arr.getJSONObject(i);
//    			String flowKey = json.containsKey("flowKey")?json.getString("flowKey"):"";
//    			String productStageValue_ = json.containsKey("productStageValue")?json.getString("productStageValue"):"";
//    			if(productStageValue_.equals(productStageValue)){
//    				processKey = flowKey;
//    				break;
//    			}
//    		}
//    		
//            if("".equals(processKey)){
//            	return "-6";
//            }
            String processDefinitionId = getFlowProcessIdByValue(productStageValue);
            System.out.println("processDefinitionId====:"+processDefinitionId);
            if("".equals(processDefinitionId)){
            	return "-6";
            }
//            String processDefinitionId = this.getFlowProcessId(processKey);
            //增加配置数据信息  动态发起流程 end
            
            sql = infoId;
            Map variablesMap = new HashMap();
            this.dealVarMap(variablesMap, new UserInfoVO(deal, userName, sendAccounts));
            Map ezFlowExtendMap = new HashMap();
            ezFlowExtendMap.put("whir_setUpHipStartTime", "");
            ezFlowExtendMap.put("remindTitle", userName + dutyUnit + "-" + materialNo + "不合格品评审记录表");
            ezFlowExtendMap.put("auto_defaultDeal_UserAccounts", defaultDealUserList);
            ezFlowExtendMap.put("auto_defaultDeal_ActivityId", "");
            ezFlowExtendMap.put("isAuto", "isAuto");
            account = ezForWork.startProcess(deal, userName, sendAccounts, processDefinitionId, sql, variablesMap, ezFlowExtendMap);
            if (account != null && !account.equals("") && !account.equals("null") && !account.equals("-1")) {
                System.out.println("========presult==============" + account);
                result = "0";
            } else {
                result = "-4";
            }

            return result;
        } else {
            result = "-5";
            return result;
        }
    }
    
    
    private void dealVarMap(Map varMap, UserInfoVO curUserInfoVO) {
        new Float("0");
        Double leadLeaderLevel_d = new Double("0");
        List leadlist = curUserInfoVO.getLeaders();
        if (leadlist != null && leadlist.size() > 0) {
            UserInfoVO leadVo = (UserInfoVO)leadlist.get(0);
            new Float(leadVo.getDutyLevel());
            leadLeaderLevel_d = new Double(leadVo.getDutyLevel());
        }

        varMap.put("condi_preTransactorDutyLevel", new Double(curUserInfoVO.getDutyLevel()));
        varMap.put("condi_preTransactorLeaderDutyLevel", leadLeaderLevel_d);
    }
    
    private String getFlowProcessIdByValue(String name) {
        String processId = "";

        try {
            this.openConn();
            String sql = "select whir$qmsConfig_gllc,whir$qmsConfig_cpjd from whir$qmsConfig where whir$qmsConfig_cpjd = ? ";
            this.stat = this.conn.prepareStatement(sql);
            this.stat.setString(1, name);
            this.rs = this.stat.executeQuery();
            if (this.rs.next()) {
                processId = this.rs.getString(1);
            }
        } catch (SQLException var12) {
            SQLException e = var12;
            e.printStackTrace();
        } finally {
            try {
                this.closeConn();
            } catch (SQLException var11) {
                SQLException e = var11;
                e.printStackTrace();
            }

        }

        return processId;
    }
    
    private String getFlowProcessId(String key) {
        String processId = "";

        try {
            this.openConn();
            String sql = "select pool_ezflowprocess_defid from ez_bpmpool_process where pool_ezflowprocess_key = ? ";
            this.stat = this.conn.prepareStatement(sql);
            this.stat.setString(1, key);
            this.rs = this.stat.executeQuery();
            if (this.rs.next()) {
                processId = this.rs.getString(1);
            }
        } catch (SQLException var12) {
            SQLException e = var12;
            e.printStackTrace();
        } finally {
            try {
                this.closeConn();
            } catch (SQLException var11) {
                SQLException e = var11;
                e.printStackTrace();
            }

        }

        return processId;
    }

    
    
    public String saveQmsForm(Element element)
    {
      String infoId = "";
      String sendAccounts = element.getChild("sendAccounts").getValue() == null ? "" : element.getChild("sendAccounts").getValue();
      String accessoryName = element.getChild("accessoryName").getValue() == null ? "" : element.getChild("accessoryName").getValue();
      String billno = element.getChild("billno").getValue() == null ? "" : element.getChild("billno").getValue();
      String sponsorUnit = element.getChild("sponsorUnit").getValue() == null ? "" : element.getChild("sponsorUnit").getValue();
      String dutyUnit = element.getChild("dutyUnit").getValue() == null ? "" : element.getChild("dutyUnit").getValue();
      String materialNo = element.getChild("materialNo").getValue() == null ? "" : element.getChild("materialNo").getValue();
      String name = element.getChild("name").getValue() == null ? "" : element.getChild("name").getValue();
      String processNo = element.getChild("processNo").getValue() == null ? "" : element.getChild("processNo").getValue();
      String deliveriesNum = element.getChild("deliveriesNum").getValue() == null ? "" : element.getChild("deliveriesNum").getValue();
      String checkNum = element.getChild("checkNum").getValue() == null ? "" : element.getChild("checkNum").getValue();
      String noNum = element.getChild("noNum").getValue() == null ? "" : element.getChild("noNum").getValue();
      String rmark = element.getChild("rmark").getValue() == null ? "" : element.getChild("rmark").getValue();
      String level = element.getChild("level").getValue() == null ? "" : element.getChild("level").getValue();
      String checkUserAccount = element.getChild("checkUserAccount").getValue() == null ? "" : element.getChild("checkUserAccount").getValue();

      String chanpinType = element.getChild("remark1").getValue() == null ? "" : element.getChild("remark1").getValue();
      System.out.println("chanpinType===" + chanpinType);
      String dataSource = "QMS";
      try {
        dataSource = element.getChild("dataSource").getValue() == null ? "QMS" : element.getChild("dataSource").getValue();
      } catch (Exception e) {
        e.printStackTrace();
      }

      boolean flag = checkQMS(billno);
      if (flag) {
        infoId = "-6";
        return infoId;
      }

      Map userMap = getUserInfoByAccounts(sendAccounts);
      String sendUserId = (String)userMap.get("userId");
      String sendUserName = (String)userMap.get("userName");
      if ((sendUserId == null) || ("".equals(sendUserId))) {
        infoId = "-1";
        return infoId;
      }
      Map orgInfo = getOrgIdByUser(sendUserId);
      String orgId = "";
      String orgFullName = "";
      if (orgInfo != null) {
        orgId = (String)orgInfo.get("orgId");
        orgFullName = (String)orgInfo.get("orgFullName");
      }

      String realAcc = "";
      if ((accessoryName != null) && (!"".equals(accessoryName.trim())))
        realAcc = modiAccFromCRM(accessoryName);
      try
      {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String dateStr = sdf.format(date);
        openConn();
        String sql = "";
        sql = "insert into whir$t3202 (whir$t3202_id,whir$t3202_owner,whir$t3202_date,whir$t3202_org,whir$t3202_workstatus,whir$t3202_f5958,whir$t3202_f5959,whir$t3202_f5960,whir$t3202_f5961,whir$t3202_f5962,whir$t3202_f5963,whir$t3202_f5964,whir$t3202_f6248,whir$t3202_f6249,whir$t3202_f5965,whir$t3202_f5999,whir$t3202_f5966,whir$t3202_f5967,whir$t3202_dataFrom,whir$t3202_f22763) values (HIBERNATE_SEQUENCE.NEXTVAL,?,?,?,'1',?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

        this.stat = this.conn.prepareStatement(sql);
        this.stat.setString(1, sendUserId);
        this.stat.setString(2, dateStr);
        this.stat.setString(3, orgId);
        this.stat.setString(4, billno);
        this.stat.setString(5, sponsorUnit);
        this.stat.setString(6, dutyUnit);
        this.stat.setString(7, materialNo);
        this.stat.setString(8, name);
        this.stat.setString(9, processNo);
        this.stat.setString(10, "".equals(deliveriesNum) ? null : deliveriesNum);
        this.stat.setString(11, "".equals(checkNum) ? null : checkNum);
        this.stat.setString(12, "".equals(noNum) ? null : noNum);
        this.stat.setString(13, rmark);
        this.stat.setString(14, realAcc);
        this.stat.setString(15, level);
        this.stat.setString(16, checkUserAccount);
        this.stat.setString(17, dataSource);
        this.stat.setString(18, chanpinType);
        this.stat.execute();

        String sql_sel = "select max(whir$t3202_id) from whir$t3202";

        this.stat = this.conn.prepareStatement(sql_sel);
        this.rs = this.stat.executeQuery();
        if (this.rs.next())
          infoId = this.rs.getString(1);
      }
      catch (SQLException e) {
        e.printStackTrace();
        infoId = "-3";
        try
        {
          closeConn();
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
      }
      finally
      {
        try
        {
          closeConn();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      return infoId;
    }
    
    
    public boolean checkQMS(String billno) {
        boolean result = false;
        Dbutil dbutil = new Dbutil();
        String sql1 = "select * from wf_work a,whir$t3202 b where a.workrecord_id=b.whir$t3202_id and b.whir$t3202_f5958 ='" + billno + "' and a.workcurstep<>'取消' and a.workcurstep<>'退回'";

        try {
            List list = dbutil.getDataListBySQL(sql1, (Map)null);
            if (list != null && list.size() > 0) {
                result = true;
            }
        } catch (Exception var6) {
            Exception e = var6;
            e.printStackTrace();
        }

        return result;
    }
    
    
    private Map<String, String> getUserInfoByAccounts(String sendAccounts) {
        Map<String, String> userMap = new HashMap();

        try {
            this.openConn();
            String sql = "select emp_id,empname from org_employee where useraccounts = ? and userisdeleted = 0";
            this.stat = this.conn.prepareStatement(sql);
            this.stat.setString(1, sendAccounts);
            this.rs = this.stat.executeQuery();
            if (this.rs.next()) {
                String userId = this.rs.getString(1);
                String userName = this.rs.getString(2);
                userMap.put("userId", userId);
                userMap.put("userName", userName);
            }
        } catch (SQLException var14) {
            SQLException e = var14;
            e.printStackTrace();
        } finally {
            try {
                this.closeConn();
            } catch (SQLException var13) {
                SQLException e = var13;
                e.printStackTrace();
            }

        }

        return userMap;
    }

    private Map<String, String> getOrgIdByUser(String sendUserId) {
        Map<String, String> map = new HashMap();

        try {
            this.openConn();
            String sql = "select oo.org_id,oo.orgnamestring from org_organization oo left join org_organization_user oou on (oo.org_id=oou.org_id) where oou.emp_id = ?";
            this.stat = this.conn.prepareStatement(sql);
            this.stat.setString(1, sendUserId);
            this.rs = this.stat.executeQuery();
            if (this.rs.next()) {
                String orgid = this.rs.getString(1);
                String orgfullname = this.rs.getString(2);
                map.put("orgId", orgid);
                map.put("orgFullName", orgfullname);
            }
        } catch (SQLException var14) {
            SQLException e = var14;
            e.printStackTrace();
        } finally {
            try {
                this.closeConn();
            } catch (SQLException var13) {
            }

        }

        return map;
    }
    
    
    private String modiAccFromCRM(String accessoryName) {
        String result = "";
        String realAcc = "";
        String saveAcc = "";
        if (accessoryName != null && !"".equals(accessoryName) && accessoryName.endsWith(";")) {
            accessoryName = accessoryName.substring(0, accessoryName.length() - 1);
        }

        String[] xArr = accessoryName.split(";");
        if (xArr != null && xArr.length > 0) {
            for(int i = 0; i < xArr.length; ++i) {
                String onlyX = xArr[i];
                String[] onlyXArr = onlyX.split("\\|");
                if (onlyXArr != null && onlyXArr.length == 2) {
                    String realName = onlyXArr[0];
                    String myRandomName = (new Random()).getRandom() + realName.substring(realName.lastIndexOf("."));
                    realAcc = realAcc + realName + ",";
                    saveAcc = saveAcc + myRandomName + ",";
                    String getAccUrl = onlyXArr[1];

                    try {
                        byte[] btImg = getImageFromNetByUrl(getAccUrl);
                        if (btImg != null && btImg.length > 0) {
                            String fileName = myRandomName;
                            String localDir = this.rootPath + File.separator + "upload" + File.separator + "customform" + File.separator + fileName.substring(0, 6);
                            File dir = new File(localDir);
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }

                            String localUrl = this.rootPath + File.separator + "upload" + File.separator + "customform" + File.separator + fileName.substring(0, 6) + File.separator + fileName;
                            writeImageToDisk(btImg, localUrl);
                            this.saveFileSize(fileName, btImg.length);
                        } else {
                            System.out.println("没有从该连接获得内容");
                        }
                    } catch (Exception var17) {
                        Exception e = var17;
                        System.out.println("下载附件失败，地址为：" + getAccUrl);
                        e.printStackTrace();
                    }
                }
            }
        }

        result = saveAcc + ";" + realAcc;
        return result;
    }
    
    
    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            String mlUrl = strUrl.substring(0, strUrl.lastIndexOf("/"));
            String ml = mlUrl.substring(mlUrl.lastIndexOf("/") + 1);
            String url1 = mlUrl.substring(0, mlUrl.lastIndexOf("/") + 1);
            String fileName = strUrl.substring(strUrl.lastIndexOf("/") + 1, strUrl.length());

            try {
                strUrl = url1 + URLEncoder.encode(ml, "UTF-8") + "/" + URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException var8) {
                UnsupportedEncodingException e = var8;
                e.printStackTrace();
            }

            System.out.println("档案附件下载地址：" + strUrl);
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            InputStream inStream = conn.getInputStream();
            return readInputStream(inStream);
        } catch (Exception var9) {
            Exception e = var9;
            e.printStackTrace();
            return null;
        }
    }
    
    
    public static void writeImageToDisk(byte[] img, String fileName) {
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                boolean var3 = file.createNewFile();
            }

            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();
        } catch (Exception var4) {
            Exception e = var4;
            e.printStackTrace();
        }

    }
    
    
    private void saveFileSize(String fileName, int length) {
        try {
            this.openConn();
            String sql = "insert into oa_allattach (FileName,filesize,encrypt,sub_folder) values (?,?,null,?)";
            this.stat = this.conn.prepareStatement(sql);
            this.stat.setString(1, fileName);
            this.stat.setInt(2, length);
            this.stat.setString(3, fileName.substring(0, 6));
            this.stat.execute();
        } catch (SQLException var15) {
            SQLException e = var15;
            e.printStackTrace();

            try {
                this.closeConn();
            } catch (SQLException var14) {
                SQLException e1 = var14;
                e1.printStackTrace();
            }
        } finally {
            try {
                this.closeConn();
            } catch (SQLException var13) {
                SQLException e = var13;
                e.printStackTrace();
            }

        }

    }
    
    
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];

        int len;
        while((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }

        inStream.close();
        return outStream.toByteArray();
    }

    public static Properties loadProperties(String filePath) {
        Properties props = new Properties();
        InputStream is = null;
        try {
            // 获取文件输入流
            is = PropertiesReader.class.getClassLoader().getResourceAsStream(filePath);
            if (is != null) {
                // 使用 UTF-8 编码的 InputStreamReader
                props.load(new InputStreamReader(is, "UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return props;
    }
    
}
